//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-2015, Egret Technology Inc.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends egret.DisplayObjectContainer {

    /**
     * 加载进度界面
     * Process interface loading
     */
    private loadingView: LoadingUI;

    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE,this.onAddToStage,this);
    }

    private onAddToStage(event: egret.Event) {
        //设置加载进度界面
        //Config to load process interface
        this.loadingView = new LoadingUI();
        this.stage.addChild(this.loadingView);

        //初始化Resource资源加载库
        //initiate Resource loading library
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE,this.onConfigComplete,this);
        RES.loadConfig("resource/default.res.json","resource/");
    }

    /**
     * 配置文件加载完成,开始预加载preload资源组。
     * configuration file loading is completed, start to pre-load the preload resource group
     */
    private onConfigComplete(event: RES.ResourceEvent): void {
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE,this.onConfigComplete,this);
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE,this.onResourceLoadComplete,this);
        RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR,this.onResourceLoadError,this);
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS,this.onResourceProgress,this);
        RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR,this.onItemLoadError,this);
        RES.loadGroup("preload");
    }

    /**
     * preload资源组加载完成
     * Preload resource group is loaded
     */
    private onResourceLoadComplete(event: RES.ResourceEvent): void {
        if(event.groupName == "preload") {
            this.stage.removeChild(this.loadingView);
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE,this.onResourceLoadComplete,this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR,this.onResourceLoadError,this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS,this.onResourceProgress,this);
            RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR,this.onItemLoadError,this);
            this.createGameScene();
        }
    }

    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onItemLoadError(event: RES.ResourceEvent): void {
        console.warn("Url:" + event.resItem.url + " has failed to load");
    }

    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onResourceLoadError(event: RES.ResourceEvent): void {
        //TODO
        console.warn("Group:" + event.groupName + " has failed to load");
        //忽略加载失败的项目
        //Ignore the loading failed projects
        this.onResourceLoadComplete(event);
    }

    /**
     * preload资源组加载进度
     * Loading process of preload resource group
     */
    private onResourceProgress(event: RES.ResourceEvent): void {
        if(event.groupName == "preload") {
            this.loadingView.setProgress(event.itemsLoaded,event.itemsTotal);
        }
    }
    private SaoLei: SaoLeiGrid;
    private time: egret.TextField;
    private count: egret.TextField;
    private operate: egret.Shape;
    private timer: egret.Timer;
    private num: number;
    private urplus: number;
    private startbtn: egret.Sprite;
    /**
     * 创建游戏场景
     * Create a game scene
     */
    private createGameScene(): void {
        this.startbtn = new egret.Sprite();
        this.startbtn.graphics.beginFill(0x000000);
        this.startbtn.graphics.drawRect(0,0,this.stage.stageWidth,this.stage.stageHeight);
        this.startbtn.graphics.endFill();

        var btn: egret.Bitmap = new egret.Bitmap();
        btn.texture = RES.getRes("sprite.观光");
        btn.width = 220;
        btn.height = 60;
        btn.x = this.stage.stageWidth / 2 - 220 / 2;
        btn.y = this.stage.stageHeight / 2 - 70 / 2 - 140;
        btn.touchEnabled = true;
        btn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.startTourist,this);
        this.startbtn.addChild(btn);
        var btn: egret.Bitmap = new egret.Bitmap();
        btn.texture = RES.getRes("sprite.简单");
        btn.width = 220;
        btn.height = 60;
        btn.x = this.stage.stageWidth / 2 - 220 / 2;
        btn.y = this.stage.stageHeight / 2 - 70 / 2 - 70;
        btn.touchEnabled = true;
        btn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.startEasy,this);
        this.startbtn.addChild(btn);
        var btn: egret.Bitmap = new egret.Bitmap();
        btn.texture = RES.getRes("sprite.标准");
        btn.width = 220;
        btn.height = 60;
        btn.x = this.stage.stageWidth / 2 - 220 / 2;
        btn.y = this.stage.stageHeight / 2 - 70 / 2;
        btn.touchEnabled = true;
        btn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.startNormal,this);
        this.startbtn.addChild(btn);
        var btn: egret.Bitmap = new egret.Bitmap();
        btn.texture = RES.getRes("sprite.挑战");
        btn.width = 220;
        btn.height = 60;
        btn.x = this.stage.stageWidth / 2 - 220 / 2;
        btn.y = this.stage.stageHeight / 2 - 70 / 2 + 70;
        btn.touchEnabled = true;
        btn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.startHard,this);
        this.startbtn.addChild(btn);
        var btn: egret.Bitmap = new egret.Bitmap();
        btn.texture = RES.getRes("sprite.终极");
        btn.width = 220;
        btn.height = 60;
        btn.x = this.stage.stageWidth / 2 - 220 / 2;
        btn.y = this.stage.stageHeight / 2 - 70 / 2 + 140;
        btn.touchEnabled = true;
        btn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.startSerious,this);
        this.startbtn.addChild(btn);
        
        
        var bg: egret.Shape = new egret.Shape();
        bg.graphics.beginFill(0xC9E5FF);
        bg.graphics.drawRect(0,30,this.stage.stageWidth,this.stage.stageHeight - 30);
        bg.graphics.endFill();
        this.addChild(bg);

        this.count = new egret.TextField();
        this.count.text = String(GV.count);
        this.count.textColor = 0x000000;
        this.count.height = 30;
        this.count.x = 5;
        this.count.y = 0;
        this.count.size = 25;
        this.count.verticalAlign = egret.VerticalAlign.MIDDLE;
        this.addChild(this.count);

        this.time = new egret.TextField();
        this.time.text = "0";
        this.time.textColor = 0x000000;
        this.time.width = this.stage.stageWidth - 5;
        this.time.height = 30;
        this.time.x = 0;
        this.time.y = 0;
        this.time.size = 25;
        this.time.textAlign = egret.HorizontalAlign.RIGHT;
        this.time.verticalAlign = egret.VerticalAlign.MIDDLE;
        this.addChild(this.time);

        var img: egret.Bitmap = new egret.Bitmap();
        img.texture = RES.getRes("sprite.红旗");
        img.width = 17.5;
        img.height = 20;
        img.x = this.stage.stageWidth / 2 - 17.5 / 2;
        img.y = 5;
        img.touchEnabled = true;
        img.addEventListener(egret.TouchEvent.TOUCH_TAP,this.changeOperate,this);
        this.addChild(img);

        this.operate = new egret.Shape();
        this.operate.graphics.lineStyle(1,0x7DB0E0);
        this.operate.graphics.drawRect(0,0,23,23);
        this.operate.graphics.endFill();
        this.operate.x = this.stage.stageWidth / 2 - 17.5 / 2 - 3;
        this.operate.y = 3;

        this.timer = new egret.Timer(1000);
        this.timer.addEventListener(egret.TimerEvent.TIMER,this.timerFunc,this);
        this.timer.addEventListener(egret.TimerEvent.TIMER_COMPLETE,this.timerComFunc,this);

        this.SaoLei = new SaoLeiGrid();
        this.SaoLei.x = 0;
        this.SaoLei.y = 30;
        this.SaoLei.addEventListener(SaoLeiEvent.PIECE_OPEN,this.onOpenEvent,this);
        this.SaoLei.addEventListener(SaoLeiEvent.PIECE_BIAOJI,this.onBiaojiEvent,this);
        this.SaoLei.addEventListener(SaoLeiEvent.PIECE_CANCEL_BIAOJI,this.onCancelBiaojiEvent,this);
        this.SaoLei.addEventListener(SaoLeiEvent.GAME_OVER,this.onGameOver,this);
        this.addChild(this.SaoLei);

        this.main();
    }
    public onOpenEvent(evt: SaoLeiEvent): void {
        if(--this.urplus <= GV.count) {
            setTimeout(() => {
                alert("恭喜，您扫完了所有的地雷，耗时：" + this.time.text + "s");
                this.stop();
                this.main();
            },100);
        }
    }
    public onGameOver(evt: SaoLeiEvent): void {
        this.SaoLei.gameOver();
        setTimeout(() => {
            alert("你被炸死了");
            this.stop();
            this.main();
        },100);
    }
    private onBiaojiEvent(evt: SaoLeiEvent): void {
        this.count.text = (this.num -= 1) >= 0 ? String(this.num) : "0";
    }
    private onCancelBiaojiEvent(evt: SaoLeiEvent): void {
        this.count.text = (this.num += 1) >= 0 ? String(this.num) : "0";
    }
    private changeOperate(evt: egret.TouchEvent): void {
        if(GV.operate === GV.O_OPEN) {
            GV.operate = GV.O_BIAOJI;
            this.addChild(this.operate);
        } else {
            GV.operate = GV.O_OPEN;
            this.removeChild(this.operate);
        }
    }
    private timerFunc(event: egret.TimerEvent) {
        this.time.text = String(event.target.currentCount);
    }

    private timerComFunc(event: egret.TimerEvent) {
        this.time.text = String(event.target.currentCount);
    }

    private main():void{
        this.addChild(this.startbtn);
    }
    private startTourist(evt: egret.TouchEvent): void {
        GV.count = 20;
        this.start();
    }
    private startEasy(evt: egret.TouchEvent): void {
        GV.count = 40;
        this.start();
    }
    private startNormal(evt: egret.TouchEvent): void {
        GV.count = 60;
        this.start();
    }
    private startHard(evt: egret.TouchEvent): void {
        GV.count = 90;
        this.start();
    }
    private startSerious(evt: egret.TouchEvent): void {
        GV.count = 110;
        this.start();
    }
    
    private start(): void {
        this.removeChild(this.startbtn);
        this.urplus = 400;
        this.num = GV.count;
        this.time.text = "0";
        this.count.text = String(GV.count);
        this.timer.reset();
        this.timer.start();
        this.SaoLei.start();
    }

    private stop(): void {
        this.timer.stop();
    }
}


